let util = require('util');
let mysqlPool = require('../dao/MySQLPool');

class PayOrderDao {
    constructor() {}

    async save(order) {
        let sql = 'insert into pay_order (uid, pay_channel, amount, out_trade_no, status, \n' +
            '                             pay_order_type, create_time, update_time, trade_type, expire_time, category)' +
            '                     values (?,   ?,           ?,      ?,            0,' +
            '                             ?,              now(),       now(),       ?,          ?,           ?)';
        let args = [order.uid, order.payChannel, order.amount, order.outTradeNo, order.payOrderType, order.tradeType, order.expireTime, order.category];
        let res = await mysqlPool.query(sql, args);
        if (res) {
            return res.insertId;
        }

        return 0;
    }

    async updateByOutTradeNoWithTx(conn, order) {
        let args = [];
        let sql = 'update pay_order set update_time = now()';
        if (order.status !== undefined) {
            args.push(order.status);
            sql += ", status = ?";
        }

        if (order.tradeNo) {
            args.push(order.tradeNo);
            sql += ", trade_no = ?";
        }

        if (order.remark) {
            args.push(order.remark);
            sql += ", remark = ?";
        }

        if (order.errCode) {
            args.push(order.errCode);
            sql += ", err_code = ?";
        }

        if (order.errMsg) {
            args.push(order.errMsg);
            sql += ", err_msg = ?";
        }

        if (order.finishTime) {
            args.push(order.finishTime);
            sql += ", finish_time = ?";
        }

        if (order.bankType) {
            args.push(order.bankType);
            sql += ", bank_type = ?";
        }

        args.push(order.out_trade_no);
        sql += " where out_trade_no = ?";

        if (order.status !== undefined && order.status === 1) {
            sql += " and status != 1";
        }
 //       console.logw("sign是: ",sql,args);
        let res = await conn.query(sql, args);
        if (res) {
            let affected = res.affectedRows;
            return affected;
        }

        return 0;
    }

    /**
     * 
     * @param {{
     *  status: Number,
     *  tradeNo: String,
     *  remark: String,
     *  errCode: String,
     *  errMsg: String,
     *  finishTime: String,
     *  bankType: String,
     *  outTradeNo: String
     *  }}} order 
     */
    async updateByOutTradeNo(order) {
        let args = [];
        let sql = 'update pay_order set update_time = now()';
        if (order.status !== undefined) {
            args.push(order.status);
            sql += ", status = ?";
        }

        if (order.tradeNo) {
            args.push(order.tradeNo);
            sql += ", trade_no = ?";
        }

        if (order.remark) {
            args.push(order.remark);
            sql += ", remark = ?";
        }

        if (order.errCode) {
            args.push(order.errCode);
            sql += ", err_code = ?";
        }

        if (order.errMsg) {
            args.push(order.errMsg);
            sql += ", err_msg = ?";
        }

        if (order.finishTime) {
            args.push(order.finishTime);
            sql += ", finish_time = ?";
        }

        if (order.bankType) {
            args.push(order.bankType);
            sql += ", bank_type = ?";
        }

        if(order.ext1){
            args.push(order.ext1);
            sql += ", ext1 = ?";
        }

        if(order.ext2){
            args.push(order.ext2);
            sql += ", ext2 = ?";
        }

        args.push(order.out_trade_no);
        sql += " where out_trade_no = ?";

        if (order.status !== undefined && order.status === 1) {
            sql += "and status != 1";
        }
  //      console.logw("聚合sql是: ",sql,args);
        let res = await mysqlPool.query(sql, args);
        if (res) {
            let affected = res.affectedRows;
            return affected;
        }

        return 0;
    }

    /**
     * 通过流水号查询订单
     * @param {String} outTradeNo 
     */
    async getByOutTradeNo(outTradeNo) {
        let sql = 'select * from pay_order where out_trade_no = ? limit 1';
        let args = [outTradeNo];
        let res = await mysqlPool.query(sql, args);
        if (res) {
            return res[0];
        }

        return null;
    }

    /**
     * 根据订单类型查询订单列表
     * @param {String} orderType
     * @returns {Promise<*>}
     */
    async queryByOrderType(orderType) {
        let sql = 'select * from pay_order where pay_order_type = ? and status = 0';
        let args = [orderType];
        let res = await mysqlPool.query(sql, args);
        if (res) {
            return res;
        }

        return [];
    }

    /**
     * 条件查询支付订单列表
     * @param {{
     *  uid:String,  // 用户uid
     *  name: String, // 用户名称
     *  mobile: String,  // 用户手机号
     *  payChannel: String,  // 支付渠道
     *  status: Number,  // 订单状态
     *  flowNo: String,  // 流水号
     *  startTime: String,
     *  endTime: String,
     *  page: Number}} cond 
     */
    async queryByCond(cond) {
        let sql = 'select p.uid, u.name, u.phone, p.amount, p.pay_channel, p.status, p.out_trade_no, p.remark, p.create_time';
        sql += "  from pay_order p ";
        sql += " left join users u on p.uid = u.uid ";
        sql += " where 1=1 ";

        let args = [];
        if (cond.uid) {
            args.push(cond.uid);
            sql += " and p.uid = ?";
        }

        if (cond.name) {
            args.push(cond.name);
            sql += " and u.name = ?";
        }

        if (cond.mobile) {
            args.push(cond.mobile);
            sql += " and u.phone = ?";
        }

        if (cond.payChannel) {
            args.push(cond.payChannel);
            sql += " and p.pay_channel = ?";
        }

        if (cond.status) {
            args.push(cond.status);
            sql += " and p.status = ?";
        }

        if (cond.flowNo) {
            args.push(cond.flowNo);
            sql += " and p.out_trade_no = ?";
        }

        if (cond.startTime){
            args.push(cond.startTime + " 00:00:00");
            sql += " and p.create_time >= ?";
        }

        if (cond.endTime){
            args.push(cond.endTime + " 23:59:59");
            sql += " and p.create_time <= ?";
        }

        sql += " order by p.id desc ";

        let pageIndex = (cond.page - 1) * 10;
        args.push(pageIndex);
        sql += " limit ?, 10";

        let res = await mysqlPool.query(sql, args);
        if (res) {
            return res;
        }

        return [];
    }

    /**
     * 
     * @param {{
     *  uid:String,  // 用户uid
     *  name: String, // 用户名称
     *  mobile: String,  // 用户手机号
     *  payChannel: String,  // 支付渠道
     *  status: Number,  // 订单状态
     *  flowNo: String,  // 流水号
     *  startTime: String,
     *  endTime: String,
     *  page: Number}} cond 
     */
    async queryByCondCnt(cond) {
        let sql = 'select count(1) cnt ';
        sql += "  from pay_order p ";
        sql += " left join users u on p.uid = u.uid ";
        sql += " where 1=1 ";

        let args = [];
        if (cond.uid) {
            args.push(cond.uid);
            sql += " and p.uid = ?";
        }

        if (cond.name) {
            args.push(cond.name);
            sql += " and u.name = ?";
        }

        if (cond.mobile) {
            args.push(cond.mobile);
            sql += " and u.phone = ?";
        }

        if (cond.payChannel) {
            args.push(cond.payChannel);
            sql += " and p.pay_channel = ?";
        }

        if (cond.status) {
            args.push(cond.status);
            sql += " and p.status = ?";
        }

        if (cond.flowNo) {
            args.push(cond.flowNo);
            sql += " and p.out_trade_no = ?";
        }

        if (cond.startTime){
            args.push(cond.startTime + " 00:00:00");
            sql += " and p.create_time >= ?";
        }

        if (cond.endTime){
            args.push(cond.endTime + " 23:59:59");
            sql += " and p.create_time <= ?";
        }

        let res = await mysqlPool.query(sql, args);
        if (res) {
            return res[0].cnt;
        }

        return 0;
    }
}

let payOrderDao = new PayOrderDao();
module.exports = payOrderDao;